<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-tag"></i> 帖子分类管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <!-- <el-input v-model="searchForm.categoryName" placeholder="分类名称" class="handle-input mr10" clearable />
        <el-input v-model="searchForm.categoryId" placeholder="分类ID" class="handle-input mr10" clearable />
        <el-date-picker v-model="searchForm.createTime" type="date" placeholder="创建时间" class="handle-input mr10"
          clearable />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button> -->
        <el-button type="primary" icon="el-icon-plus" @click="showAddCategory">新增帖子分类</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="categoryTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="分类ID" width="120" />
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column prop="createTime" label="创建时间" >
          <template #default="scope">
            {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="showEditCategory(scope.row)">编辑</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑帖子分类弹窗 -->
    <el-dialog v-model="categoryDialog.visible" :title="categoryDialog.isEdit ? '编辑帖子分类' : '新增帖子分类'" width="600px">
      <el-form :model="categoryDialog.form" :rules="categoryRules" ref="categoryForm" label-width="120px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryDialog.form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { getPostCategories, addPostCategory, updatePostCategory, deletePostCategory } from "@/api/content";

export default {
  name: "PostClassification",
  data() {
    return {
      searchForm: {
        categoryName: "",
        categoryId: "",
        createTime: "",
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 帖子分类弹窗
      categoryDialog: {
        visible: false,
        isEdit: false,
        editId: null,
        form: {
          categoryName: "",
        },
      },
      // 表单验证规则
      categoryRules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.categoryName) {
        params.categoryName = this.searchForm.categoryName;
      }
      if (this.searchForm.categoryId) {
        params.id = this.searchForm.categoryId;
      }
      if (this.searchForm.createTime) {
        params.createTime = moment(this.searchForm.createTime).format('YYYY-MM-DD');
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getPostCategories(params);

        if (response && response.data) {
          this.tableData = response.data.rows || response.data;

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取帖子分类数据失败:', error);
        this.$message.error('获取帖子分类数据失败');
      }
    },
    showAddCategory() {
      this.categoryDialog.visible = true;
      this.categoryDialog.isEdit = false;
      this.categoryDialog.editId = null;
      this.categoryDialog.form = {
        categoryName: "",
      };
      this.$nextTick(() => {
        this.$refs.categoryForm?.clearValidate();
      });
    },
    showEditCategory(row) {
      this.categoryDialog.visible = true;
      this.categoryDialog.isEdit = true;
      this.categoryDialog.editId = row.id;
      this.categoryDialog.form = {
        categoryName: row.categoryName || "",
      };
      this.$nextTick(() => {
        this.$refs.categoryForm?.clearValidate();
      });
    },
    saveCategory() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              ...this.categoryDialog.form,
              // createTime: new Date().toISOString()
            };

            if (this.categoryDialog.isEdit) {
              params.id = this.categoryDialog.editId;
              await updatePostCategory(params);
              this.$message.success('编辑帖子分类成功');
            } else {
              await addPostCategory(params);
              this.$message.success('新增帖子分类成功');
            }

            this.categoryDialog.visible = false;
            this.getData();
          } catch (error) {
            console.error('保存帖子分类失败:', error);
            this.$message.error('保存帖子分类失败');
          }
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`确定要删除帖子分类"${row.categoryName}"吗？`, "提示", {
        type: "warning"
      }).then(async () => {
        try {
          await deletePostCategory({ id: row.id });
          this.$message.success('删除帖子分类成功');
          this.getData();
        } catch (error) {
          console.error('删除帖子分类失败:', error);
          this.$message.error('删除帖子分类失败');
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}
</style>